<?php
declare (strict_types = 1);

namespace app\wx\controller;
use EasyWeChat\Kernel\Messages\Message;
use think\facade\Log;
use app\common\model\Config;
class Server extends WxBase
{
    protected $memberModel;
    protected function initialize()
    {
        parent::initialize();
        $this->memberModel = new \app\auth\model\Member;
    }
    public function index()
    {
        // 设置响应器
        $this->app->server->push(function($message){
            switch ($message['MsgType']) {
                case 'event':
                    return $this->EventHandle($message);
                    break;
                case 'text':
                    return $this->TextHandle($message);
                    break;
                case 'image':
                    return '收到图片消息';
                    break;
                case 'voice':
                    return '收到语音消息';
                    break;
                case 'video':
                    return '收到视频消息';
                    break;
                case 'location':
                    return '收到坐标消息';
                    break;
                case 'link':
                    return '收到链接消息';
                    break;
                case 'file':
                    return '收到文件消息';
                // ... 其它消息
                default:
                    return '收到其它消息';
                    break;
            }
        });
        // $this->app->server->push([$this,'TextHandle'],Message::TEXT);
        // $this->app->server->push([$this,'EventHandle'],Message::EVENT);
        
        // 配置响应
        $response = $this->app->server->serve();
        $response->send();
        exit;
    }
    public function EventHandle($message) {
        switch($message['Event']) {
          case 'subscribe': 
            return $this->EventSubscribeHandle($message);
            break;
          case 'unsubscribe':
            return $this->EventUnsubscribeHandle($message);
            break;
          default: break;
        }
      }
      public function TextHandle($message) {
        $content = Config::where('name', 'wx_reply_auto')->cache(true)->value('value');
        return $content === null ? '您好！欢迎关注！' : $content;
      }
      /**
       * 订阅事件处理函数
       *
       * @return void
       */
      public function EventSubscribeHandle($message) {
        $userinfo = $this->app->user->get($message['FromUserName']);
        $this->memberModel->saveSubscribeInfo($userinfo);
        $content = Config::where('name', 'wx_reply_sub')->cache(true)->value('value');
        return $content === null ? '您好！欢迎关注！' : $content;
      }
      public function EventUnsubscribeHandle($message) {
        $userinfo = $this->app->user->get($message['FromUserName']);
        $this->memberModel->saveSubscribeInfo($userinfo);
        return '取消关注成功！';
      }
}
